using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using ShopForWeb.Model.Basic;
using ShopForWeb.Services;
using ShopForWeb.UI.Models;
using ShopForWeb.UI.Utils.Extensions;
using ShopForWeb.UI.Utils.Filters;

namespace ShopForWeb.UI.Controllers.Test
{
    [Route("[controller]")]
    [UserInfo]
    [UserAuthroize]
    public class ShopCarController : Controller
    {
        private readonly ILogger<ShopCarController> _logger;
        private ShopCarService _shopCarService;

        public ShopCarController(ILogger<ShopCarController> logger,ShopCarService shopCarService)
        {
            _logger = logger;
            _shopCarService=shopCarService;
        }

    [HttpGet]
     public async Task<IActionResult> IndexAsync()
     {
        long userId = this.GetUser()?.UserId ?? 0;
         var result = await _shopCarService.GetAllAsync((int)userId);
         ViewBag.ShopCarList=result;
        //return Json(result);
         return View();
     }

      [HttpPost]
      public async Task<IActionResult> AddNew([FromForm] ShopCar car)
     {
       car.UserId = this.GetUser()?.UserId ?? 0;
        int result = await _shopCarService.AddNewAsync(car);
        if (result == 1)
         return Json(new ResponseViewModel()
         {
            Code = 200,
            Message = "购物车商品添加成功"

         });
        else
           return Json(new ResponseViewModel()
          {
            Code = 500,
            Message = "购物车商品添加失败"

           });
      }


        [HttpDelete("{productId}/{userId}")]
         public async Task<IActionResult> RemoveCartOrder([FromRoute] long productId, [FromRoute] long userId)
        {
           int result = await _shopCarService.RemoveAsync((int)productId, (int)userId);
           if (result == 1)
           return Json(new ResponseViewModel()
           {
              Code = 200,
               Message = "用户购物车订单删除成功"
           });
           else
            return Json(new ResponseViewModel()
            {
              Code = 500,
               Message = "用户购物车订单删除失败"
            });
        }

        [HttpDelete("clear/{userId}")]
        public async Task<IActionResult> Clear(long userId)
        {
           var result = await _shopCarService.ClearAsync((int)userId);
            if (result > 0)
                return Json(new ResponseViewModel()
                 {
                     Code = 200,
                    Message = "购物车一键清除成功"
               });
              else
                 return Json(new ResponseViewModel()
              {
                 Code = 500,
                 Message = "购物车一键清除失败"
              });
         }
       
    }
}